package com.example.hxds.common.fallback;

import cn.hutool.json.JSONUtil;
import com.example.hxds.common.api.DriverApi;
import com.example.hxds.common.dto.RegisterNewDriverDTO;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.R;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class DriverApiFallbackFactory implements FallbackFactory<DriverApi> {

    // TODO 了解一下openfeign获取远程服务自定义异常的原理（看看有没有好的定制方案挖掘）

    @Override
    public DriverApi create(Throwable throwable) {
        return new DriverApi(){
            R getDetailMsg() {
                if (throwable instanceof FeignException) {
                    FeignException feignException = (FeignException) throwable;
                    String contentUTF8 = feignException.contentUTF8();
                    HxdsException hxdsException = JSONUtil.parse(contentUTF8).toBean(HxdsException.class);
                    String msg = hxdsException.getMsg();
                    int code = hxdsException.getCode();
                    return R.error(code, msg);
                } else {
                    return R.error();
                }
            };

            @Override
            public R registerNewDriver(RegisterNewDriverDTO registerNewDriverDTO) {
                return getDetailMsg();
            }
        };

    }
}
